<style lang="scss" scoped>
	.share {
		width: 750upx;
		margin-top: 20upx;
		margin-bottom: 200upx;
	}

	.uni-textarea {
		margin: 20upx 50upx;
		padding: 20upx;
		border-radius: 10upx;
		border: 1upx solid #ccc;
	}

	.pics {
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;
		justify-content: flex-start;
		align-items: center;
		align-content: center;
		padding-top: 20upx;
		padding-bottom: 20upx;
		padding-left: 46upx;

		.medias {
			width: 210upx;
			height: 210upx;
			background-color: #eee;
			border-radius: 6upx;
			margin: 5upx;
			position: relative;

			.iclose {
				position: absolute;
				right: 0;
				top: 0;
				background-color: rgba($color: #333, $alpha: 0.6);
				border-bottom-left-radius: 100%;
				padding: 10upx 10upx 16upx 16upx;
				z-index: 999;
			}
		}

		.img {
			width: 210upx;
			height: 210upx;
			border-radius: 6upx;
		}

		.video {
			width: 210upx;
			height: 210upx;
			border-radius: 6upx;
		}

		.uploadBtn {
			width: 210upx;
			height: 210upx;
			background-color: #eee;
			border-radius: 6upx;
			margin: 5upx;
			display: flex;
			flex-direction: column;
			flex-wrap: wrap;
			justify-content: center;
			align-items: center;
			align-content: center;

			.text {
				color: #888;
				font-size: 24upx;
				margin-top: 20upx;
			}
		}
	}

	.chose-product {
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;
		justify-content: space-between;
		padding: 10upx 20upx 10upx 0;
		align-items: center;
		align-content: center;
		margin-left: 50upx;
		width: 440upx;
		height: 60upx;
		line-height: 60upx;
		border-radius: 30upx;
		font-size: 24upx;
		color: #888;
		border: 1upx solid #eee;
		background-color: #eee;

		.left {
			display: flex;
			flex-direction: row;
			flex-wrap: wrap;
			justify-content: center;
			width: 80upx;
			height: 60upx;
			line-height: 60upx;
			border-top-left-radius: 30upx;
			border-bottom-left-radius: 30upx;
			background-color: #e6e6e6;
		}
	}

	.btns {
		width: 700upx;
		position: fixed;
		bottom: 40upx;
		left: 25upx;
	}
</style>
<template>
	<view class="share">
		<!-- 内容输入框 -->
		<view class="uni-textarea">
			<textarea placeholder-style="color:#AAAAAA" placeholder="添加描述..." @input="bindTextAreaInput" />
			</view>
    <!-- 选择商品 -->
    <view class="chose-product" v-if="choseProductTag">
      <view class="left" @tap="pickerShow = true">
        <u-icon name="bag-fill" color="#999" size="32"></u-icon>
      </view>
      <view class="name" @tap="pickerShow = true">{{productList[myPciker]}}</view>
      <u-icon name="close-circle-fill" color="#ccc" size="40" @tap="cancelChoseProduct"></u-icon>
    </view>
    <!-- 内容发布 -->
    <view class="pics">
      <!-- 图片选择及发布相关 -->
      <template v-if="uploadType == 'imgs' ">
        <view class="medias" v-for="( image, index ) in uploadPicsList" :key="index">
          <image
            class="img"
            :src="image.path"
            :data-src="image"
            @tap="previewImage(index)"
            mode="aspectFill"
          />
          <u-icon name="close" class="iclose" color="#eee" size="20" @tap="removeImage(index)" />
        </view>
        <!-- 选择照片按钮 -->
        <view class="uploadBtn" @tap="chosePicsAndUpload" v-if="uploadPicsList.length < 9">
          <u-icon name="plus" size="60" color="#aaa" />
          <view class="text">选择照片</view>
        </view>
      </template>

      <!-- 视频选择及发布相关 -->
      <template v-if="uploadType == 'video' ">
        <view class="medias" v-if="!!uploadVideo.tempFilePath">
          <video
            class="video"
            :src="uploadVideo.tempFilePath"
            object-fit="cover"
            :autoplay="false"
            :controls="false"
          />
          <u-icon name="close" class="iclose" color="#eee" size="20" @tap="removeVideo()" />
        </view>
        <view class="uploadBtn" @tap="choseVideoAndUpload" v-if="!uploadVideo.tempFilePath ">
          <u-icon name="plus" size="60" color="#aaa" />
          <view class="text">选择视频</view>
        </view>
      </template>
    </view>

    <view class="btns">
      <u-button type="primary" size="default" @click="sendFeed" :disabled="uploadStatus">发布动态</u-button>
    </view>
    <u-picker mode="selector" v-model="pickerShow" :range="productList" @confirm="choseProduct"></u-picker>
    <!-- 未登录登陆组件 -->
    <login ref="login"></login>
  </view>
</template>

<script>
import uploadFile from "../common/uploadFile.js";
import constConfig from "../common/constConfig.js";
export default {
  data() {
    return {
      // 发布内容描述
      feedInfo: "",
	  // 关联活动的ID
	  activity_id: 0,

      // 是否取消显示商品卡
      choseProductTag: true,
      // 是否显示商品选项卡
      pickerShow: false,
      // 选项卡参数
      productList: constConfig.productList,
      // 选项卡选择内容
      myPciker: 0,
      myChoseProd: 0,

      // 上传类型
      uploadType: "imgs",
      // 文件上传地址
      uploadUrl: "https://sns.royole.fun/api/v2/storage",
      // 预置图片上传列表
      uploadPicsList: [],
      // 预置视频上传列表
      uploadVideo: {},
      // 发布状态控制器
      uploadStatus: false,
    };
  },
  async onLoad(params) {
    await this.$u.api.checkLogin();
	
	// 是否允许 UGC 选择商品选项卡？或者是指定的商户才有选择选项卡能力？
	let user = await this.$u.api.getCurrentUser();
	if(!!user.is_vedio && user.is_vedio == 1){
		this.choseProductTag = true;
	}else{
		this.choseProductTag = false;
	}
	
	
	if(params.id){
		this.activity_id = params.id
	}
    if (params.type == "视频") {
      this.uploadType = "video";
    } else {
      this.uploadType = "imgs";
    }
  },
  methods: {
    // textarea 输入内容获取
    bindTextAreaInput(e) {
      this.feedInfo = e.detail.value;
    },
    // 选择 关联商品
    choseProduct(e) {
      this.myPciker = e[0];
      this.myChoseProd = this.myPciker;
    },
    // 取消 关联商品
    cancelChoseProduct() {
      this.myChoseProd = -1;
      this.choseProductTag = false;
    },
    // 选择视频并上传
    choseVideoAndUpload() {
      // 上传视频
      uni.chooseVideo({
        maxDuration: 60,
        count: 1,
        camera: "back",
        // 视频是否压缩
        compressed: true,
        // 视频来源类型
        sourceType: ["album", "camera"],
        success: (res) => {
          this.uploadVideo = res;
        },
      });
    },
    // 选择并上传图片
    chosePicsAndUpload() {
      let count = 9 - this.uploadPicsList.length;
      if (this.uploadPicsList.length >= 9) {
        uni.showToast({
          title: "最多选择9张照片",
          icon: "success",
          duration: 1000,
        });
        count = 0;
        return false;
      }
      uni.chooseImage({
        count, //默认9
        sizeType: ["compressed"], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ["album", "camera"], //从相册选择
        success: (res) => {
          console.log(res.tempFiles);
          this.uploadPicsList = [...this.uploadPicsList, ...res.tempFiles];
          if (this.uploadPicsList.length > 9) {
            this.uploadPicsList = this.uploadPicsList.slice(0, 9);
          }
        },
      });
    },
    // 预览图片
    previewImage(index) {
      console.log(index);
      //预览图片
      var current = this.uploadPicsList[index].path;
      let urls = [];
      this.uploadPicsList.map((item) => {
        urls.push(item.path);
      });
      uni.previewImage({
        current: current,
        urls,
      });
    },
    // 删除图片
    removeImage(index) {
      this.uploadPicsList.splice(index, 1);
    },
    // 上传视频
    removeVideo() {
      this.uploadVideo = {};
    },
    // 发布动态
    async sendFeed() {
      // 如果未登录则先登录
      let loginStatus = await this.$u.api.checkLogin();
      if (!loginStatus) {
        uni.hideToast();
        uni.showToast({
          title: "请先登录",
          icon: "loading",
          duration: 1500,
        });
        return;
      }
      // 如果正在上传中则等待
      if (this.uploadStatus) return;
      this.uploadStatus = true;
      // 如果描述为空则不进行发布
      if (this.feedInfo == "") {
        uni.showToast({
          title: "描述不能为空",
          icon: "loading",
          duration: 1000,
        });
        this.uploadStatus = false;
        return;
      }
	  // 内容安全审核
	  const checkRes = await wx.serviceMarket.invokeService({
	  	service: 'wxee446d7507c68b11',
	  	api: 'msgSecCheck',
	  	data: {
	  	  "Action": 'TextApproval',
	  	  "Text": this.feedInfo,
	  	}
	  });
	  if(checkRes.data.Response.EvilTokens.length >0 ){
	  	uni.hideToast();
	  	uni.showModal({
	  	    title: '发布失败',
	  	    content: '您分享的内容涉及敏感信息：“'+checkRes.data.Response.EvilTokens[0].EvilKeywords[0]+"”",
	  	    success: function (res) {
	  	        uni.navigateBack({
	  	        	delta: 1
	  	        })
	  	    }
	  	});
		// 数据埋点
		this.$$Rangers.event('content_publish', {
			content_type:this.uploadType == "video" ? '视频':'图片',
			is_success: false,
			has_goods_tag: this.choseProductTag,
			entrance:'小程序客户端',
			fail_reason:'文字内容审核不通过',
		    platform: '小程序',
		})
	  	this.uploadStatus = false;
	  	return;
	  }

      if (this.uploadType == "video") {
        if (!this.uploadVideo.tempFilePath) {
          uni.showToast({
            title: "请选择短视频",
            icon: "loading",
            duration: 1000,
          });
          this.uploadStatus = false;
          return;
        }
        if (this.uploadVideo.duration > 60) {
          uni.hideToast();
          uni.showToast({
            title: "短视频太长",
            icon: "loading",
            duration: 1500,
          });
		  // 数据埋点
		  this.$$Rangers.event('content_publish', {
		  	content_type:this.uploadType == "video" ? '视频':'图片',
		  	is_success: false,
		  	has_goods_tag: this.choseProductTag,
		  	entrance:'小程序客户端',
		  	fail_reason:'短视频超过60秒',
		      platform: '小程序',
		  })
          this.uploadStatus = false;
          return false;
        }
        uni.showToast({
          title: "视频上传中...",
          icon: "loading",
          duration: 60000,
        });
        // console.log(this.uploadVideo);
        let res = await uploadFile(
          this.uploadVideo.tempFilePath,
          this.uploadVideo.size,
          this.uploadUrl
        );
        if (!res) {
			// 数据埋点
			this.$$Rangers.event('content_publish', {
				content_type:this.uploadType == "video" ? '视频':'图片',
				is_success: false,
				has_goods_tag: this.choseProductTag,
				entrance:'小程序客户端',
				fail_reason:'视频上传服务器失败',
			    platform: '小程序',
			})
          uni.hideToast();
          uni.showToast({
            title: "视频上传失败",
            icon: "loading",
            duration: 1500,
          });
          this.uploadStatus = false;
          return false;
        }
        let pres = await this.$u.api.postOneFeed({
          feed_content: this.feedInfo,
          feed_from: 5,
          feed_mark: new Date().getTime(),
          topics: [],
          video: {
            cover: "",
            resource: res.data.node,
          },
          product_id: this.myChoseProd,
        });
        // console.log(pres)
        if (!!pres && pres.message == "发布成功") {
			// 数据埋点
			this.$$Rangers.event('content_publish', {
				content_type:this.uploadType == "video" ? '视频':'图片',
				is_success: true,
				has_goods_tag: this.choseProductTag,
				entrance:'小程序客户端',
				fail_reason:'上传成功',
			    platform: '小程序',
			})
          uni.hideToast();
          uni.showToast({
            title: "视频发布成功",
            icon: "success",
            duration: 1000,
            success: () => {
			  // 通知动态瀑布流 更新了
			  uni.$emit("addOneFeed");
              // 通知个人中心 动态数量更新了
              uni.$emit("userFeddsNumChange", {
                data: 1,
              });
              this.uploadStatus = false;
              // uni.switchTab({
              //   url: "/pages/newUser",
              // });
			  uni.navigateBack({
			  	delta: 1
			  })
            },
          });
        } else {
			// 数据埋点
			this.$$Rangers.event('content_publish', {
				content_type:this.uploadType == "video" ? '视频':'图片',
				is_success: false,
				has_goods_tag: this.choseProductTag,
				entrance:'小程序客户端',
				fail_reason:'发布动态写入系统失败',
			    platform: '小程序',
			})
          uni.hideToast();
          uni.showToast({
            title: "视频发布失败",
            icon: "loading",
            duration: 1500,
          });
          this.uploadStatus = false;
        }
      } else {
        console.log(this.activity_id)
        if (this.uploadPicsList.length <= 0 && this.activity_id == 0) {
          uni.showToast({
            title: "请选择照片",
            icon: "loading",
            duration: 1000,
          });
          this.uploadStatus = false;
          return;
        }
        uni.showToast({
          title: "动态发布中...",
          icon: "loading",
          duration: 60000,
        });
        let upStatusArr = [];
        // 循环遍历上传多图
        this.uploadPicsList.map((item) => {
          upStatusArr.push(uploadFile(item.path, item.size, this.uploadUrl));
        });
        let images = [];
        (await Promise.all(upStatusArr)).map((item) => {
          images.push(item.data.node);
        });
        // console.log(images)
        let pres = await this.$u.api.postOneFeed({
          feed_content: this.feedInfo,
		  activity_id: this.activity_id,
          feed_from: 5,
          feed_mark: new Date().getTime(),
          topics: [],
          images,
          product_id: this.myChoseProd,
        });
		// 图片安全审核
        if(pres.id == 0){
			// 数据埋点
			this.$$Rangers.event('content_publish', {
				content_type:this.uploadType == "video" ? '视频':'图片',
				is_success: false,
				has_goods_tag: this.choseProductTag,
				entrance:'小程序客户端',
				fail_reason:'图片涉及敏感信息',
			    platform: '小程序',
			})
			uni.hideToast();
			uni.showModal({
			    title: '发布失败',
			    content: '您分享的图片涉及敏感信息',
			    success: function (res) {
			        uni.navigateBack({
			        	delta: 1
			        })
			    }
			});
			this.uploadStatus = false;
			return;
		}

        if (!!pres && pres.message == "发布成功") {
			// 数据埋点
			this.$$Rangers.event('content_publish', {
				content_type:this.uploadType == "video" ? '视频':'图片',
				is_success: true,
				has_goods_tag: this.choseProductTag,
				entrance:'小程序客户端',
				fail_reason:'发布成功',
			    platform: '小程序',
			})
          uni.hideToast();
          uni.showToast({
            title: "照片发布成功",
            icon: "success",
            duration: 1000,
            success: () => {
              // 通知个人中心 动态数量更新了
              uni.$emit("userFeddsNumChange");
			  // 通知动态瀑布流 更新了
			  uni.$emit("addOneFeed");
              this.uploadStatus = false;
              // uni.switchTab({
              //   url: "/pages/newUser",
              // });
			  uni.$emit('activity:feed:posted')
			  uni.navigateBack({
			  	delta: 1
			  })
            },
          });
        } else {
			// 数据埋点
			this.$$Rangers.event('content_publish', {
				content_type:this.uploadType == "video" ? '视频':'图片',
				is_success: false,
				has_goods_tag: this.choseProductTag,
				entrance:'小程序客户端',
				fail_reason:'图片动态写入数据库失败',
			    platform: '小程序',
			})
          uni.hideToast();
          uni.showToast({
            title: "照片发布失败",
            icon: "loading",
            duration: 1500,
          });
          this.uploadStatus = false;
        }
      }
    },
  },
};
</script>
